package com.zjut.an.admin.action;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.zjut.an.admin.dao.AnAdmin;
import com.zjut.an.admin.manager.AnAdminManager;
import com.zjut.an.config.manager.AnConfigManager;
import com.zjut.an.log.dao.AnLog;
import com.zjut.an.log.manager.AnLogManager;
import com.zjut.an.role.manager.AnRoleManager;
import com.zjut.an.util.module.PageModule;
import com.zjut.an.util.system.Status;
import com.zjut.an.util.tools.DateUtil;
import com.zjut.an.util.tools.JSONUtilClass;
import com.zjut.an.util.tools.JSONUtilClassTime;
import com.zjut.an.util.tools.MD5;
import com.zjut.zs.school.dao.ZsSchool;
import com.zjut.zs.school.manager.ZsSchoolManager;
import com.zjut.zs.user.dao.ZsUser;

public class AnAdminAction extends ActionSupport implements
ServletResponseAware, ServletRequestAware, ModelDriven<AnAdmin>{

	private HttpServletRequest request;
	private HttpServletResponse response;
	private HttpSession session;
	
	private AnAdmin obj;
	private Map<String , Object> dataMap;
	private int page = 1, limit = 10;
	private String order;
	private String sort;
	private String search;
	private String rowstr;
	
	@Resource(name = "AnAdminManager")
	private AnAdminManager manager;
	
	@Resource(name = "AnRoleManager")
	private AnRoleManager roManager;

	@Resource(name = "ZsSchoolManager")
	private ZsSchoolManager zsManager;
	
	@Resource(name = "AnLogManager")
	private AnLogManager logManager;
	
	@Resource(name = "MD5")
	private MD5 md5;
	
	@Resource(name = "AnConfigManager")
	private AnConfigManager anconfig;
	
	@Resource(name = "DateUtil")
	private DateUtil dateutil;
	
	public String anAdminList() throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		dataMap = new HashMap<String, Object>();
		if (session.getAttribute("admin")!=null) {//只有管理员才允许执行该操作，以免信息泄露
			if(search!=null) {
				obj = new AnAdmin();
				obj.setAccount(search);
			}
			
			PageModule module = manager.getDataByInstance(page, limit, sort, order, obj);
			dataMap.put("rows", module.getObjects());
			dataMap.put("total", module.getTotal()); 
		}		
		obj = null; 
		return SUCCESS;
	}
	
	@SuppressWarnings("unchecked")
	public String anAdminDeletes() throws UnsupportedEncodingException {
		if (session.getAttribute("admin")!=null) {//只有管理员才允许执行该操作，以免信息泄露
			request.setCharacterEncoding("UTF-8");
			String objumniJSON = rowstr;
			List list = JSONUtilClassTime.getDTOList(objumniJSON, AnAdmin.class);
			manager.deleteDatas(list);
			AnLog log = new AnLog("系统日志",((AnAdmin)session.getAttribute("admin")).getAccount()+"于"+dateutil.getCurrentDate5()+" 批量删除"+((AnAdmin)list.get(0)).getAccount()+"账号信息成功", dateutil.getCurrentDate5());
			logManager.addData(log);
			dataMap = new HashMap<String, Object>();
			dataMap.put("flag", "success");
		}		
		return SUCCESS;
	}
	
	public String anAdminAdd() throws UnsupportedEncodingException {
		if (session.getAttribute("admin")!=null) {//只有管理员才允许执行该操作，以免信息泄露
			request.setCharacterEncoding("UTF-8");
			String objumniJSON = rowstr;
			obj = (AnAdmin)JSONUtilClass.getDTO(objumniJSON, AnAdmin.class);
			obj.setPassword(md5.toMD5(obj.getPassword()));
			obj.setLastlogin(dateutil.getCurrentDate5());
			manager.addData(obj);
			AnLog log = new AnLog("系统日志",((AnAdmin)session.getAttribute("admin")).getAccount()+"于"+dateutil.getCurrentDate5()+" 添加"+obj.getAccount()+"账号信息成功", dateutil.getCurrentDate5());
			logManager.addData(log);
			dataMap = new HashMap<String, Object>();
			dataMap.put("flag", "success");
		}		
		return SUCCESS;
	}
	
	public String anAdminDelete() throws UnsupportedEncodingException {
		if (session.getAttribute("admin")!=null) {//只有管理员才允许执行该操作，以免信息泄露
			request.setCharacterEncoding("UTF-8");
			String objumniJSON = rowstr;
			obj = (AnAdmin)JSONUtilClass.getDTO(objumniJSON, AnAdmin.class);
			manager.deleteData(obj);
			AnLog log = new AnLog("系统日志",((AnAdmin)session.getAttribute("admin")).getAccount()+"于"+dateutil.getCurrentDate5()+" 删除"+obj.getAccount()+"账号信息成功", dateutil.getCurrentDate5());
			logManager.addData(log);
			dataMap = new HashMap<String, Object>();
			dataMap.put("flag", "success");
		}		
		return SUCCESS;
	}
	
	public String anAdminUpdate() throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		String objumniJSON = rowstr;
		AnAdmin admin = (AnAdmin)JSONUtilClassTime.getDTO(objumniJSON, AnAdmin.class);
		if (session.getAttribute("admin")!=null) {
			if (((AnAdmin)session.getAttribute("admin")).getAccount().equals("admin") || ((AnAdmin)session.getAttribute("admin")).getAccount().equals(admin.getAccount())) {//系统管理员或者本人
				obj = manager.getData(admin.getAdId());
				if (!admin.getPassword().equals(obj.getPassword())) {
					admin.setPassword(md5.toMD5(admin.getPassword()));
				} else {
					admin.setPassword(obj.getPassword());
				}
				manager.updateData(admin);
				AnLog log = new AnLog("系统日志",((AnAdmin)session.getAttribute("admin")).getAccount()+"于"+dateutil.getCurrentDate5()+" 修改"+admin.getAccount()+"账号信息成功", dateutil.getCurrentDate5());
				logManager.addData(log);
			}
		}
		obj=null;
		return SUCCESS;
	}
	
	public String anAdminSave() throws UnsupportedEncodingException {
		obj = (AnAdmin)(JSONUtilClass.getDTOArray(rowstr, AnAdmin.class)[0]);
		if (obj.getAdId()!=null) {
			return anAdminUpdate();
		} else {
			return anAdminAdd();
		}
	}
	
	
	public String anAdminLogin() {
		System.out.println("-------AdminLogin-------");
		dataMap = new HashMap<String, Object>();
		String adminJSON = rowstr;
		System.out.println("rand---"+JSONUtilClass.getMapFromJson(adminJSON).get("rand"));
		System.out.println(adminJSON);
		try {
			Calendar a=Calendar.getInstance();
			String sqm = "swyt"+a.get(a.YEAR);
			obj = (AnAdmin)JSONUtilClass.getDTO(adminJSON, AnAdmin.class);
			String password = URLDecoder.decode(obj.getPassword(),"utf-8");
			//System.out.println("登陆："+password+ " | "+md5.toMD5(password)+" | ");
			if (!md5.toMD5(sqm).equals(anconfig.getSingleConfigInfoByName("授权码"))) {
				System.out.println("授权码校验:" + md5.toMD5(sqm) + " "+anconfig.getSingleConfigInfoByName("授权码"));
				dataMap.put("message", "sqmfailed");
			} else if ("是".equals(anconfig.getSingleConfigInfoByName("管理登录是否启用短信验证码")) && !this.checkCode(JSONUtilClass.getMapFromJson(adminJSON).get("code"), session.getAttribute("code"))) {
				dataMap.put("flag", "success");
				dataMap.put("message", "randfailed");
			} else if (!"是".equals(anconfig.getSingleConfigInfoByName("管理登录是否启用短信验证码")) && !this.checkCode(JSONUtilClass.getMapFromJson(adminJSON).get("rand"), session.getAttribute("rand"))) {
				dataMap.put("flag", "success");
				dataMap.put("message", "randfailed");
			} else if (null==obj.getPassword() || obj.getPassword().trim().length()==0) {
				dataMap.put("message", "pswnullfailed");
			} else {	
				obj.setPassword(null);
				PageModule pm = manager.getDataByInstance(1, 1, null,null,obj);				
				if (pm.getTotal()>0) {	
					System.out.println("校验登录间隔");
					obj = (AnAdmin)pm.getObjects().get(0);
					boolean timeactive = true;
					if (null!=obj.getLastlogin()) {//首先验证登录间隔
						DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
						Date olddate = format.parse(obj.getLastlogin());
						Date newdate = new Date();
						Calendar c1 = Calendar.getInstance();
				        Calendar c2 = Calendar.getInstance();
				        c1.setTime(olddate);
				        c2.setTime(newdate);
				        System.out.println("现在时间："+newdate +" 上次冻结时间："+ olddate);
				        int timelong = ((c2.get(Calendar.DAY_OF_YEAR) - c1.get(Calendar.DAY_OF_YEAR))*24*60*60 + (c2.get(Calendar.HOUR) - c1.get(Calendar.HOUR))*60*60 +(c2.get(Calendar.MINUTE) - c1.get(Calendar.MINUTE))*60+(c2.get(Calendar.SECOND) - c1.get(Calendar.SECOND)));
				        System.out.println("时间间隔："+timelong+"秒");
				        
				        int count = 5;
				        if(null==obj.getEmail()) {//如果错误登录次数为空默认设置0
				        	obj.setEmail("0");
				        }
				        if ("是".equals(anconfig.getSingleConfigInfoByName("启用登录错误冻结"))&& Integer.parseInt(obj.getEmail())>=count && timelong<60) {//距离上次密码或者身份错误小于60秒
				        	System.out.println("冻结中");
				        	dataMap.put("message", "timefailed");
				        	timeactive = false;
				        } 
				        if (timeactive) {//如果间隔时间允许
				        	//System.out.println("登陆："+obj.getPassword()+ " | "+md5.toMD5(password)+" | ");
				        	if (obj.getPassword().equals(md5.toMD5(password)) && Status.ADMIN_ON.getStatus().equals(obj.getActive())) {
				        		System.out.println("登陆成功");
				        		obj.setLastlogin(dateutil.getCurrentDate5());
					        	obj.setEmail("0");
								manager.updateData(obj);
								session.setAttribute("admin", obj);
								session.setAttribute("role", roManager.getData(obj.getRoId()));
								session.setAttribute("adminrole", Status.ROLE_SYSTEM.getStatus());
								session.setAttribute("admincaname", obj.getAccount());								
								ZsSchool sc = new ZsSchool();
								ZsSchool scobj = (ZsSchool)zsManager.getDataByInstance(1,1,null,null,sc).getObjects().get(0);
								session.setAttribute("school", scobj);
								session.removeAttribute("code");
								System.out.println("登陆："+obj.getAccount()+ " | "+obj.getTruename()+" | ");
								AnLog log = new AnLog("系统日志",obj.getAccount()+"于"+dateutil.getCurrentDate5()+" 登陆成功", dateutil.getCurrentDate5());
								logManager.addData(log);
								dataMap.put("message", "success");
				        	} else {//密码错误或者被冻结
				        		System.out.println("密码错误或者被冻结");
				        		if(Integer.valueOf(obj.getEmail())>=5) {//重置错误次数
				        			obj.setEmail("0");
				        		}
				        		obj.setLastlogin(dateutil.getCurrentDate5());
				        		obj.setEmail(String.valueOf(Integer.valueOf(obj.getEmail())+1));
				        		System.out.println("登录错误尝试次数："+obj.getEmail());
								manager.updateData(obj);
								dataMap.put("message", "pswfailed");
				        	}
						}			        
					}
				} else {
					dataMap.put("message", "accountfailed");
				}
			}	
			obj=null;
		} catch (Exception e) {
			e.printStackTrace();
			dataMap.put("message", "failed");
		}
		return SUCCESS;
	}
	
	public String resetAdminPassword() throws UnsupportedEncodingException {//用于IE6
		System.out.println("-------AdminLogin-------");
		request.setCharacterEncoding("UTF-8");
		String objumniJSON = rowstr;
		AnAdmin admin = (AnAdmin)JSONUtilClassTime.getDTO(objumniJSON, AnAdmin.class);
		if (session.getAttribute("admin")!=null) {
			if (((AnAdmin)session.getAttribute("admin")).getAccount().equals("admin") || ((AnAdmin)session.getAttribute("admin")).getAccount().equals(admin.getAccount())) {//系统管理员或者本人
				obj = manager.getData(admin.getAdId());
				if (!admin.getPassword().equals(obj.getPassword())) {
					obj.setPassword(md5.toMD5(admin.getPassword()));
				}
				obj.setTruename(admin.getTruename());
				obj.setPhone(admin.getPhone());
				obj.setEmail(admin.getEmail());
				manager.updateData(obj);
				AnLog log = new AnLog("系统日志",((AnAdmin)session.getAttribute("admin")).getAccount()+"于"+dateutil.getCurrentDate5()+" 修改"+admin.getAccount()+"账号信息成功", dateutil.getCurrentDate5());
				logManager.addData(log);
			}
		}
		obj=null;
		dataMap = new HashMap<String, Object>();
		dataMap.put("flag", "success");
		return SUCCESS;
	}
	
	public String anAdminCount() {//用于外部用户注册时候进行账号验证，以避免使用list泄露信息
		try {
			request.setCharacterEncoding("UTF-8");
			dataMap = new HashMap<String, Object>();
			PageModule module = manager.getDataByInstance(page, limit, sort, order, obj);
			//dataMap.put("rows", module.getObjects());
			dataMap.put("total", module.getTotal()); 
			obj = null; 
			return SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}		
	}
	
	private boolean checkCode(Object input, Object sessioncode) {
		if (null!=input && null!=sessioncode && input.toString().equals(sessioncode.toString())) {
			return true;
		} else {
			return false;
		}
	}
	
	@Override
	public AnAdmin getModel() {
		if (null == obj) {
			obj = new AnAdmin();
		}
		return obj;
	}

	@Override
	public void setServletRequest(HttpServletRequest arg0) {
		request = arg0;
		session = request.getSession();
	}

	@Override
	public void setServletResponse(HttpServletResponse arg0) {
		response = arg0;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	public HttpSession getSession() {
		return session;
	}

	public void setSession(HttpSession session) {
		this.session = session;
	}

	public AnAdmin getAl() {
		return obj;
	}

	public void setAl(AnAdmin obj) {
		this.obj = obj;
	}

	public Map<String, Object> getDataMap() {
		return dataMap;
	}

	public void setDataMap(Map<String, Object> dataMap) {
		this.dataMap = dataMap;
	}

	public String getRowstr() {
		return rowstr;
	}

	public void setRowstr(String rowstr) {
		this.rowstr = rowstr;
	}

	public AnAdminManager getManager() {
		return manager;
	}

	public void setManager(AnAdminManager manager) {
		this.manager = manager;
	}
	
	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public String getOrder() {
		return order;
	}

	public void setOrder(String order) {
		this.order = order;
	}

	public String getSort() {
		return sort;
	}

	public void setSort(String sort) {
		this.sort = sort;
	}

	public String getSearch() {
		return search;
	}

	public void setSearch(String search) {
		this.search = search;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

}
